#!/usr/bin/env python
"""

    6frame_translation.py
    [--log_file PATH]
    [--quiet]

"""

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from optparse import OptionParser
import sys, os
import os.path
import StringIO

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))
    import platform
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules", platform.architecture()[0])))
    module_name = os.path.split(sys.argv[0])[1]
    module_name = os.path.splitext(module_name)[0];
else:
    module_name = __name__

import get_command_line
from options import check_mandatory_options


if __name__ == '__main__':
    parser = OptionParser(version="%prog 1.0", usage = "\n\n    %progs [options]")
    #   general options: verbosity / logging
    # 
    parser.add_option("-v", "--verbose", dest = "verbose",
                      action="store_true", default=False,
                      help="Do not echo to shell but only print to log.")
    parser.add_option("-L", "--log_file", dest="log_file",
                      metavar="FILE", 
                      type="string",
                      help="name and path of log file")
    parser.add_option("--skip_parameter_logging", dest="skip_parameter_logging",
                        action="store_true", default=False,
                        help="Do not print program parameters to log.")
    parser.add_option("--debug", dest="debug",
                        action="store_true", default=False,
                        help="Set default program parameters in debugging mode.")
    
    
    
    
    #parser.set_defaults(log_file       = os.path.join("logs", "split_genome_files.log"))
    #parser.set_defaults(log_parameters = True)
    
    
    # get help string
    f =StringIO.StringIO()
    parser.print_help(f)
    helpstr = f.getvalue()
    (options, remaining_args) = parser.parse_args()
    
    if options.debug:
        test_dir = "/net/cpp-group/Leo/bin/src/python_modules/test/test_6frame_translation"
        options.log_file       = os.path.join(test_dir, "6frame_translation.log")
        options.log_parameters = True
    
    
    mandatory_options = []
            
    # mandatory options
    check_mandatory_options (options, mandatory_options, helpstr)


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

import StringIO
import re
import operator

from collections import defaultdict
import logging
from lg_program_logging import setup_std_logging
from options import get_option_strings

import json

from ctranslate_by_codon import translate
from filter_string import Translator
from reverse_complement_dna import reverse_complement
from fasta_sequences_iterator import fasta_sequences_iterator 
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

def six_frame_translation(instream, outstream):
    """
    Output translation in all 3 frames, and with reverse complement
    for sequences in fasta format
    """
    trans = Translator(frm="agct-.hmrwyn", to="AGCT-.HMRWYN", keep="agcthmrwynAGCT-.HMRWYN")
    for seq_id, seq in fasta_sequences_iterator(instream):
        t_seq = trans(seq)
        for strand in 1, 0:
            for frame in 0,1,2:
                outstream.write(">%s:frame=%d:strand=%d\n%s\n" % (
                                    seq_id, frame, strand, translate(t_seq[frame:])))
            t_seq = reverse_complement(t_seq)


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Logger


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

if __name__ == '__main__':

    logger = logging.getLogger(module_name)
    setup_std_logging(logger, options.log_file, options.verbose)


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
            
if __name__ == '__main__':
    
    if not options.skip_parameter_logging:
        programme_name = os.path.split(sys.argv[0])[1]
        logger.info("%s %s" % (programme_name, " ".join(get_option_strings(parser, options))))

    six_frame_translation(sys.stdin,  sys.stdout)
                


